package pl.edu.pw.stud.ltrzaska.config;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import pl.edu.pw.stud.ltrzaska.policy.xml.XmlConverter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class Config {
	private static final String FILE_APP_CONFIG_XML = "appConfig.xml";
	private static final Logger LOGGER = Logger.getLogger(XmlConverter.class);
	private static Config instance;
	private AppConfiguration appConfig;
	
	private Config() {
	}

	private static Config getInstance() {
		if(instance == null) {
			instance = new Config();
		}
		return instance;
	}
	
	public static AppConfiguration getAppConfig() {
		Config t = getInstance();
		if(t.appConfig == null) {
			t.appConfig = getInstance().load();
		}
		return t.appConfig;
	}
	
	public AppConfiguration load() {
		String xml = null;
		try {
			xml = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(FILE_APP_CONFIG_XML));
		} catch (FileNotFoundException e) {
			LOGGER.error("", e);
		} catch (IOException e) {
			LOGGER.error("", e);
		}

		XStream xstream = initXStream();

		AppConfiguration ac = null;
		try {
			ac = (AppConfiguration) xstream.fromXML(xml);
		} catch (XStreamException e) {
			LOGGER.error("", e);
		}
		return ac;
	}

	private XStream initXStream() {
		XStream xstream = new XStream(new DomDriver());

		xstream.alias("fspolicy-configuration", AppConfiguration.class);
		xstream.aliasField("attribute-definitions", AppConfiguration.class, "attrDefinitions");

		xstream.alias("attribute", AttributeDefinition.class);
		xstream.aliasField("xml-name", AttributeDefinition.class, "xmlName");		
		xstream.aliasField("in-class", AttributeDefinition.class, "clazz");		
		xstream.aliasField("java-name", AttributeDefinition.class, "javaName");		
		
		return xstream;
	}
}
